//
//  BindingPhoneViewController.m
//  yigou
//
//  Created by 秦乾龙 on 17/2/7.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "BindingPhoneViewController.h"
#import "NextChangePhoneViewController.h"
#import "AFNetworking.h"//主要用于网络请求方法
#import "UIKit+AFNetworking.h"//里面有异步加载图片的方法
#import "AFHTTPSessionManager.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "NavView.h"
#import "ZYButton.h"

@interface BindingPhoneViewController ()<UITextFieldDelegate>
@property (nonatomic,strong) NSArray *dataAray;
//@property (nonatomic,strong) TagView *tagView;
@property (nonatomic,strong) NSArray *selectedArray;
@property (nonatomic,strong) UITextField *codeField;
@property (nonatomic,strong) UITextField *phoneField;
@property (nonatomic,retain) UITextField *newphoneField;
@property (nonatomic,strong) NSString *codeStr;
@property (nonatomic,retain) UITextField *psdField;

@end

@implementation BindingPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setUI];
}
- (void) setUI
{
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"绑定手机号"];
    
//    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(backClick)];
//    self.navigationItem.leftBarButtonItem = backBtn;
    UIBarButtonItem * backButtonItem = [[UIBarButtonItem alloc] init];
    [backButtonItem setTitle:@""];
    self.navigationItem.leftBarButtonItem = backButtonItem;
    
    UIButton *buttonNotice = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonNotice.frame = CGRectMake(0, 0, 40, 20);
    buttonNotice.titleLabel.font = [UIFont systemFontOfSize:15];
    [buttonNotice setTitle:@"确定" forState:UIControlStateNormal];
    
    UIBarButtonItem *btnNoticeItem = [[UIBarButtonItem alloc]initWithCustomView:buttonNotice];
    [buttonNotice addTarget:self action:@selector(changeClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = btnNoticeItem;
    
    UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH)];
    backgroundView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0f];
    [self.view addSubview:backgroundView];
//    UIView *phoneView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 100*kScale)];
//    phoneView.backgroundColor = [UIColor whiteColor];
//    [backgroundView addSubview:phoneView];
//    UILabel *titleLable = [[UILabel alloc]init];
//    titleLable.text = @"当前绑定手机号:";
//    titleLable.font = [UIFont systemFontOfSize:15];
//    CGSize titleLableSize = [titleLable sizeThatFits:CGSizeMake(MAXFLOAT, 100*kScale)];
//    titleLable.frame = CGRectMake(30*kScale, 0, titleLableSize.width, 100*kScale);
//    [phoneView addSubview:titleLable];
//    _phoneField = [[UITextField alloc]init];
//    _phoneField.delegate = self;
//    _phoneField.font = [UIFont systemFontOfSize:15];
//    //    _phoneField.placeholder = @"请输入新手机号码";
//    _phoneField.frame = CGRectMake(30*kScale*2+titleLableSize.width,0,ScreenW, 100*kScale);
//    [phoneView addSubview:_phoneField];
    
    UIView *newPhoneView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 100*kScale)];
    newPhoneView.backgroundColor = [UIColor whiteColor];
    [backgroundView addSubview:newPhoneView];
    _newphoneField = [[UITextField alloc]init];
    _newphoneField.delegate = self;
    _newphoneField.font = [UIFont systemFontOfSize:15];
    _newphoneField.placeholder = @"请输入手机号码";
    _newphoneField.keyboardType = UIKeyboardTypePhonePad;
    _newphoneField.frame = CGRectMake(30*kScale, 0, ScreenW-30*kScale, 100*kScale);
    _newphoneField.tag = 10;
    [newPhoneView addSubview:_newphoneField];
    
    CGFloat codeBtnW = 100;
    UIView *codeView = [[UIView alloc]initWithFrame:CGRectMake(0, 102*kScale, ScreenW, 100*kScale)];
    codeView.backgroundColor = [UIColor whiteColor];
    [backgroundView addSubview:codeView];
    
    _codeField = [[UITextField alloc]init];
    _codeField.delegate = self;
    _codeField.tag = 11;
    _codeField.font = [UIFont systemFontOfSize:15];
    _codeField.frame = CGRectMake(30*kScale, 0, ScreenW-30*kScale*2-codeBtnW, 100*kScale);
    _codeField.placeholder = @"请输入验证码";
    _codeField.keyboardType = UIKeyboardTypeNumberPad;
    [codeView addSubview:_codeField];
   
    UIButton *codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    codeBtn.frame = CGRectMake(ScreenW-codeBtnW, 0, codeBtnW, 100*kScale);
    //    codeBtn setTitle:@"获取验证码" forState:ui
    [codeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    codeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [codeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
    [codeBtn addTarget:self action:@selector(getCode) forControlEvents:UIControlEventTouchUpInside];
    [codeView addSubview:codeBtn];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(ScreenW-codeBtnW-20*kScale, 10*kScale, 6*kScale, 80*kScale)];
    lineView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0f];
    [codeView addSubview:lineView];
    
    UIView *newPsdView = [[UIView alloc]initWithFrame:CGRectMake(0, 204*kScale, ScreenW, 100*kScale)];
    newPsdView.backgroundColor = [UIColor whiteColor];
    [backgroundView addSubview:newPsdView];
    _psdField = [[UITextField alloc]init];
    _psdField.delegate = self;
    _psdField.font = [UIFont systemFontOfSize:15];
    
    _psdField.placeholder = @"请输入6位以上密码";
    _psdField.frame = CGRectMake(30*kScale, 0, ScreenW-3*30*kScale-42*kScale, 100*kScale);
    _psdField.keyboardType = UIKeyboardTypeASCIICapable;
    [newPsdView addSubview:_psdField];
    UIButton *eyeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    eyeBtn.frame = CGRectMake(ScreenW-30*kScale-42*kScale, 29*kScale, 42*kScale, 42*kScale);
    [eyeBtn setImage:[UIImage imageNamed:@"眼"] forState:UIControlStateNormal];
    [eyeBtn addTarget:self action:@selector(eyeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [newPsdView addSubview:eyeBtn];
}
//获取验证码
- (void)request
{
//    [_userFiled.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *urlStr = [[NSString stringWithFormat:@"%@/sys/login/memberRegistr/sms/randomCode?mobile_no=%@",APIYIGOU,[_newphoneField.text stringByReplacingOccurrencesOfString:@" " withString:@""]]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        
        NSLog(@"77777%@",allDic);
        [ViewFactory showSuccess:@"已发送"];
        _codeStr = allDic[@"data"];
        //测试
        //_codeField.text = allDic[@"data"];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showInfoMsg:@"验证码发送失败"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

- (void)backClick {
    [self.navigationController popToRootViewControllerAnimated:YES];
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSLog(@"%@",NSStringFromRange(range));
    if (textField.tag==10)
    {
        if (textField) {
            NSString* text = textField.text;
            //删除
            if([string isEqualToString:@""]){
                
                //删除一位
                if(range.length == 1){
                    //最后一位,遇到空格则多删除一次
                    if (range.location == text.length-1 ) {
                        if ([text characterAtIndex:text.length-1] == ' ') {
                            [textField deleteBackward];
                        }
                        return YES;
                    }
                    //从中间删除
                    else{
                        NSInteger offset = range.location;
                        
                        if (range.location < text.length && [text characterAtIndex:range.location] == ' ' && [textField.selectedTextRange isEmpty]) {
                            [textField deleteBackward];
                            offset --;
                        }
                        [textField deleteBackward];
                        textField.text = [self parseString:textField.text];
                        UITextPosition *newPos = [textField positionFromPosition:textField.beginningOfDocument offset:offset];
                        textField.selectedTextRange = [textField textRangeFromPosition:newPos toPosition:newPos];
                        return NO;
                    }
                }
                else if (range.length > 1) {
                    BOOL isLast = NO;
                    //如果是从最后一位开始
                    if(range.location + range.length == textField.text.length ){
                        isLast = YES;
                    }
                    [textField deleteBackward];
                    textField.text = [self parseString:textField.text];
                    
                    NSInteger offset = range.location;
                    if (range.location == 3 || range.location  == 8) {
                        offset ++;
                    }
                    if (isLast) {
                        //光标直接在最后一位了
                    }else{
                        UITextPosition *newPos = [textField positionFromPosition:textField.beginningOfDocument offset:offset];
                        textField.selectedTextRange = [textField textRangeFromPosition:newPos toPosition:newPos];
                    }
                    
                    return NO;
                }
                
                else{
                    return YES;
                }
            }
            
            else if(string.length >0){
                
                //限制输入字符个数
                if (([self noneSpaseString:textField.text].length + string.length - range.length > 11) ) {
                    return NO;
                }
                //判断是否是纯数字(千杀的搜狗，百度输入法，数字键盘居然可以输入其他字符)
                //            if(![string isNum]){
                //                return NO;
                //            }
                [textField insertText:string];
                textField.text = [self parseString:textField.text];
                
                NSInteger offset = range.location + string.length;
                if (range.location == 3 || range.location  == 8) {
                    offset ++;
                }
                UITextPosition *newPos = [textField positionFromPosition:textField.beginningOfDocument offset:offset];
                textField.selectedTextRange = [textField textRangeFromPosition:newPos toPosition:newPos];
                return NO;
            }else{
                return YES;
            }
            
        }
    }
    
    
    return YES;
    
}
-(NSString*)noneSpaseString:(NSString*)string
{
    return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}

- (NSString*)parseString:(NSString*)string
{
    if (!string) {
        return nil;
    }
    NSMutableString* mStr = [NSMutableString stringWithString:[string stringByReplacingOccurrencesOfString:@" " withString:@""]];
    if (mStr.length >3) {
        [mStr insertString:@" " atIndex:3];
    }if (mStr.length > 8) {
        [mStr insertString:@" " atIndex:8];
        
    }
    
    return  mStr;
}
- (void)changeClick
{
    if (_psdField.text.length<6||_newphoneField.text.length<11||_codeField.text.length<1) {
        [ViewFactory showInfoMsg:@"请输入完整信息"];
        return;
    }
    
    if ([_codeField.text isEqualToString:_codeStr]) {
        NSString *urlStr = [[NSString stringWithFormat:@"%@/userCenter/modifyMemberMobile?user_mobile_no=%@&reg_num=%@&user_pwd=%@",APIYIGOU,[_newphoneField.text stringByReplacingOccurrencesOfString:@" " withString:@""],_codeStr,_psdField.text]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        DYBaseRequest *request = [DYBaseRequest new];
        request.requestUrl = urlStr;
        [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
            NSLog(@"allDic===%@",allDic);
                
            [ViewFactory showSuccess:@"绑定成功"];
            [self.navigationController popToRootViewControllerAnimated:YES];
        } error:^(YTKBaseRequest *request) {
            [ViewFactory showErrorStrMsg:@"绑定失败"];
        } failure:^(YTKBaseRequest *request) {
            [ViewFactory showErrorStrMsg:NETWORK_ERR];
        }];
            
    }
    else
    {
        [ViewFactory showInfoMsg:@"请输入正确验证码"];
    }
        
}
- (void)getCode
{
    [self request];
}
//密码显示
- (void)eyeBtnClick:(UIButton*)sender
{
    if (sender.selected==YES) {
        sender.selected = NO;
        _psdField.secureTextEntry = YES;
    }
    else
    {
        sender.selected = YES;
        _psdField.secureTextEntry = NO;
    }
}
//键盘
- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_phoneField  resignFirstResponder];
    [_codeField resignFirstResponder];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
